package com.sheng.project.study.genericity;

import java.lang.reflect.Field;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.List;

/**
 * @author liusheng
 * @date 2023/07/06
 */
public class Demo9 {

    List<String>[] list;

    public static void main(String[] args) throws NoSuchFieldException {
        Field list = Demo9.class.getDeclaredField("list");
        // 获取字段的泛型类型
        Type genericType = list.getGenericType();
        // 看看字段的具体泛型类型
        System.out.println(genericType.getClass());
        if (genericType instanceof GenericArrayType) {
            GenericArrayType genericArrayType = (GenericArrayType) genericType;
            // 获取数组的具体类型，具体的类型就是 List<String>，这个是个泛型类型，对应 java 中的 ParameterizedType 接口
            Type genericComponentType = genericArrayType.getGenericComponentType();
            System.out.println(genericComponentType.getClass());
            if (genericComponentType instanceof ParameterizedType) {
                ParameterizedType parameterizedType = (ParameterizedType) genericComponentType;
                System.out.println(parameterizedType.getRawType());
                // 调用 getActualTypeArguments() 获取 List<String> 中尖括号中的参数列表
                Type[] actualTypeArguments = parameterizedType.getActualTypeArguments();
                for (Type actualTypeArgument : actualTypeArguments) {
                    System.out.println(actualTypeArgument.getTypeName());
                }
                System.out.println(parameterizedType.getOwnerType());
            }
        }
    }
}
